//
//  SEGIAnalyticsLogErrorDBManager.m
//  test
//
//  Created by 刘山 on 2017/12/3.
//  Copyright © 2017年 刘山. All rights reserved.
//

#import "SEGIAnalyticsLogErrorDBManager.h"

#if __has_include(<Commom/SEGModel.h>)
#import <Commom/SEGModel.h>
#else
#import "SEGModel.h"
#endif

static NSString* SEGIAnalyticsLogErrorDBName = @"SEGLogErrorDBName";//数据库名
static NSString* SEGIAnalyticsLogErrorTableName = @"SEGLogErrorTableName";//数据表名

@implementation SEGIAnalyticsLogErrorDBManager
/**
 * 创建错误日志统计数据表
 * @author Sam
 */
+(void)segLogErrorCreateTable{
    
    if([self isTableOK:SEGIAnalyticsLogErrorTableName DB:SEGIAnalyticsLogErrorDBName])return;
    
    NSArray *allKeys = [self segAllKeysFromModel:[SEGIAnalyticsLogErrorModel class]];
    
    NSMutableString *sql = [NSMutableString string];
    [sql appendString:[NSString stringWithFormat:@"CREATE TABLE %@ (",SEGIAnalyticsLogErrorTableName]];
    [allKeys enumerateObjectsUsingBlock:^(NSString*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *content = (idx == allKeys.count - 1) ? [NSString stringWithFormat:@" %@ TEXT ",obj] : [NSString stringWithFormat:@" %@ TEXT ,",obj];
        [sql appendString:content];
    }];
    [sql appendString:@");"];
    
    [self segCreateTableWithDBName:SEGIAnalyticsLogErrorDBName WithTable:sql];
}

/**
 * 把错误日志数据保存的本地数据库
 * @author Sam
 * @param data  事件
 */
+(BOOL)segLogErrorInsertWithData:(SEGIAnalyticsLogErrorModel*)data{
    NSDictionary *dataJson = [data yy_modelToJSONObject];
    return [self segInsertWithDictionary:dataJson DBName:SEGIAnalyticsLogErrorDBName WithTable:SEGIAnalyticsLogErrorTableName];
}

/**
 * 所有数据库中所有错误日志数据
 * @author Sam
 */
+(NSArray*)segLogErrorQuryAll{
    NSString *querySql = [NSString stringWithFormat:@"SELECT * FROM %@ ;",SEGIAnalyticsLogErrorTableName];
    NSArray *data = [self segExecuteQueryWithDBName:SEGIAnalyticsLogErrorDBName WithSQL:querySql OfValues:nil];
    
    if (data && data.count > 0) {
        return data;
    }
    
    return nil;
}


/**
 * 删除所有数据
 * @author Sam
 */
+(BOOL)segDeleteAll{
    
    NSString *delSql = [NSString stringWithFormat:@"DELETE FROM %@;",SEGIAnalyticsLogErrorTableName];
    return [self segExecuteDB:SEGIAnalyticsLogErrorDBName WithSQL:delSql OfValues:nil];
}

@end
